package com.arpa.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.jpush.api.utils.StringUtils;
import com.arpa.ntocc.common.common.cache.AreaCache;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.ShopCache;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.dto.ShopDTO;
import com.arpa.wms.domain.dto.ShopauditDTO;
import com.arpa.wms.domain.entity.Shop;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.ShopVO;
import com.arpa.wms.mapper.ShopMapper;
import com.arpa.wms.service.IShopService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.ServerException;
import java.util.*;

/**
 * <p>
 * 店铺 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2021-2-22
 */
@Service()
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final AreaCache areaCache;

    private final ShopCache shopCache;

    private final PartyCache partyCache;
    public ShopServiceImpl(AreaCache areaCache, ShopCache shopCache, PartyCache partyCache) {
        this.areaCache = areaCache;
        this.shopCache = shopCache;
        this.partyCache = partyCache;
    }
    private static final String SHOP_NAME_MANAGE = "店铺名称不能重复！";
    private static final String SHOP_CODE_MANAGE = "店铺编码不能重复！";
    private static final String SHOP_CODE_NAME = "店铺编码不能与名称重复！";

    /**
     * 查询列表
     *
     * @param shopDTO
     * @return
     */
    @Override
    public List<ShopVO> queryList(ShopDTO shopDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StringUtils.isNotEmpty(shopDTO.getSortField())) {
            shopDTO.setSortField(CommonUtil.camel2Underline(shopDTO.getSortField()));
        }
        return baseMapper.queryList(shopDTO);
    }

    /**
     * 查询合计,包含总数
     *
     * @param shopDTO
     * @return
     */
    @Override
    public ShopVO queryListSum(ShopDTO shopDTO) {
        return baseMapper.queryListSum(shopDTO);
    }

    /**
     * 新增
     * @param shop
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insert(Shop shop){
        //校验授权仓库code和货主code不能为空
        ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
        Integer sum = baseMapper.selectCount(new LambdaQueryWrapper<Shop>().eq(Shop::getShopCode, shop.getShopCode()).eq(Shop::getGroupCode,UserUtil.getBranchCode()));
        if (sum>0){
            throw new ServiceException(SHOP_CODE_MANAGE);
        }
        String shipmentCode = UserUtil.getBranchCode();
        if(ObjectUtil.isNotNull(shipmentCode)) {
            getUserloginShipment(Collections.singletonList(shipmentCode));
        }
        Integer nameSum = baseMapper.selectCount(new LambdaQueryWrapper<Shop>().eq(Shop::getName, shop.getName()).in(Shop::getShipmentCode,UserUtil.getAuthorizeShipmentCodes()).eq(Shop::getGroupCode,UserUtil.getBranchCode()));
        if (nameSum > 0) {
            throw new ServiceException(SHOP_NAME_MANAGE);
        }
        shop.setGroupCode(UserUtil.getBranchCode());
        shop.setStatus(StatusEnum.ACTIVE.getValue());
        shop.setCode(IdUtil.simpleUUID());
        shop.setGroupCode(UserUtil.getBranchCode());
        shop.setCreatedBy(UserUtil.getCode());
        shop.setCreatedName(partyCache.translate(UserUtil.getCode()));
        return baseMapper.insert(shop);
    }

    /**
     * 获取供应商授权的供应商列表
     *
     * @param shipmentCodes
     * @return
     */
    @Override
    public List<Map<String, Object>> getUserloginShipment(List<String> shipmentCodes) {
        return baseMapper.getUserloginShipment(shipmentCodes);
    }

    /**
     * 更新
     * @param shop
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int update(Shop shop){
        //店铺状态为审核未通过时，更新状态为待审核
        if (CommonConst.STR_TWO.equals(shop.getStatus())) {
            shop.setStatus(CommonConst.STR_ZERO);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("code", shop.getCode());
        shop.setModifiedBy(UserUtil.getCode());
        shop.setModifiedName(partyCache.translate(UserUtil.getCode()));
        shopCache.flushCache(shop.getCode(),shop.getShipmentCode());
        return baseMapper.update(shop, new QueryWrapper<Shop>().allEq(params));
    }


    /**
     * 通过code查询店铺信息
     * 使用缓存查询
     * @param code
     * @return
     */
    @Override
    public ShopVO getOneInfo(String code) {
        Shop entity = baseMapper.selectOne(new QueryWrapper<Shop>().lambda().eq(Shop::getCode,code).eq(Shop::getGroupCode,UserUtil.getBranchCode()));
        Optional.ofNullable(entity).orElseThrow(() -> new ServiceException("没有查询到信息"));
        ShopVO shopVO = new ShopVO();
        BeanUtil.copyProperties(entity, shopVO);
        List<String> areaList = new ArrayList<>();
        areaList.add(entity.getProvince());
        areaList.add(entity.getCity());
        areaList.add(entity.getCounty());
        String areaStr = "";

        if (StrUtil.isNotBlank(entity.getProvince())) {
            if (StrUtil.isNotBlank(areaStr)) {
                areaStr = areaStr + "/" + areaCache.translateProvince(entity.getProvince());
            } else {
                areaStr = areaCache.translateProvince(entity.getProvince());
            }
        }
        if (StrUtil.isNotBlank(entity.getCity())) {
            if (StrUtil.isNotBlank(areaStr)) {
                areaStr = areaStr + "/" + areaCache.translateCity(entity.getCity());
            } else {
                areaStr = areaCache.translateCity(entity.getCity());
            }
        }
        if (StrUtil.isNotBlank(entity.getCounty())) {
            if (StrUtil.isNotBlank(areaStr)) {
                areaStr = areaStr + "/" + areaCache.translateCounty(entity.getCounty());
            } else {
                areaStr = areaCache.translateCounty(entity.getCounty());
            }
        }

        shopVO.setAreaList(areaList);
        return shopVO;
    }




}
